package com.guomei.configs;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

@Configuration
public class PaymentConfig {
    private final AlipayConfig alipayConfig;
    private final WechatPayConfig wechatPayConfig;

    public PaymentConfig(AlipayConfig alipayConfig, WechatPayConfig wechatPayConfig) {
        this.alipayConfig = alipayConfig;
        this.wechatPayConfig = wechatPayConfig;
    }

    /**
     * 支付宝客户端
     */
    @Bean
    public AlipayClient alipayClient() {
        return new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),
                "json",
                StandardCharsets.UTF_8.name(),
                alipayConfig.getPublicKey(),
                "RSA2"
        );
    }

    /**
     * 微信支付客户端
     */
    @Bean
    public CloseableHttpClient wechatPayClient() throws Exception {
        // 加载商户私钥
        PrivateKey merchantPrivateKey = getPrivateKey(wechatPayConfig.getPrivateKeyPath());

        // 构建认证器
        WechatPay2Credentials credentials = new WechatPay2Credentials(
                wechatPayConfig.getMchId(),
                new PrivateKeySigner(wechatPayConfig.getMchSerialNo(), merchantPrivateKey)
        );

        // 获取证书管理器
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
        certificatesManager.putMerchant(
                wechatPayConfig.getMchId(),
                credentials,
                wechatPayConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8)
        );

        // 获取验签器
        Verifier verifier = certificatesManager.getVerifier(wechatPayConfig.getMchId());

        // 构建http客户端
        return WechatPayHttpClientBuilder.create()
                .withMerchant(wechatPayConfig.getMchId(), wechatPayConfig.getMchSerialNo(), merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
    }

    /**
     * 加载私钥
     */
    private PrivateKey getPrivateKey(String filename) throws GeneralSecurityException, IOException {
        String content;
        
        // 判断是否为绝对路径
        if (filename.startsWith("/") || filename.contains(":")) {
            // 绝对路径，直接读取
            content = new String(Files.readAllBytes(Paths.get(filename)), StandardCharsets.UTF_8);
        } else {
            // 相对路径，使用ClassPathResource
            content = new String(Files.readAllBytes(Paths.get(new ClassPathResource(filename).getURI())), StandardCharsets.UTF_8);
        }
        
        return com.wechat.pay.contrib.apache.httpclient.util.PemUtil.loadPrivateKey(
                content.replace("-----BEGIN PRIVATE KEY-----", "")
                        .replace("-----END PRIVATE KEY-----", "")
                        .replaceAll("\\s+", "")
        );
    }
}
